/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.repository;

import com.google.appengine.api.datastore.Key;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ro.futurefeed.model.User;

/**
 *
 * @author Alex
 */
@Repository
@Transactional
public class UserRepositoryImpl implements UserRepository {
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public User save(User user) {
        entityManager.persist(user);
        return user;
    }

    @Override
    public User update(User user) {
        user = entityManager.merge(user);
        
        return user;
    }

    @Override
    @Transactional(readOnly=true)
    public User findByFBId(String fbId) {
        Query query = entityManager.createQuery("select u from User u where u.fbId = :facebookId");
        query.setParameter("facebookId", fbId);
        
        try{
            User user = (User) query.getSingleResult();
            return user;
        }catch(NoResultException e){
            return null;
        }
    }

    @Override
    @Transactional(readOnly=true)
    public User findByKey(Key userId) {
        Query query = entityManager.createQuery("select u from User u where u.id = :userKey");
        query.setParameter("userKey", userId);
        
        try{
            User user = (User) query.getSingleResult();
            return user;
        }catch(NoResultException e){
            return null;
        }
    }
    
}
